﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using Win8Demo.Helper;
using Win8Demo.Parser;
using Windows.Data.Json;
using Windows.Networking.Connectivity;

namespace Win8Demo.NetWork
{
    public class NetEngine : IDisposable
    {
        #region Fields
        private HttpClient _httpClient;
        #endregion

        #region Properties
        public CommonReqEntity ReqEntity { get; set; }
        public BaseParser Parser { get; set; }
        public Dictionary<string, object> ResultData { get; set; }
        public WebCallback Callback { get; set; }
        #endregion

        #region Constructor
        public NetEngine(CommonReqEntity reqEntity, BaseParser parser, Dictionary<string, object> resultData, WebCallback callback)
        {
            this.ReqEntity = reqEntity;
            this.Parser = parser;
            this.ResultData = resultData;
            this.Callback = callback;
            _httpClient = new HttpClient();
        }
        #endregion

        #region Method
        public async Task<int> Request()
        {
            int result;
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                result = -1;
            }
            else
            {
                HttpResponseMessage message = null;
                try
                {
                    //TODO 此处要加上AES加密
                    if (ReqEntity.RequestType == ReqType.GET)
                    {
                        message = await _httpClient.GetAsync(string.Concat(ReqEntity.Url,"?",ParamHelper.BuildParas(ReqEntity.Paras)));
                    }
                    else if (ReqEntity.RequestType == ReqType.POST)
                    {
                        message = await _httpClient.PostAsync(ReqEntity.Url, new StringContent(ParamHelper.BuildParas(ReqEntity.Paras)));
                    }
                    message.EnsureSuccessStatusCode();
                    string jsonStr = await message.Content.ReadAsStringAsync();
                    JsonObject source = JsonObject.Parse(jsonStr);
                    this.Parser.ParseData(source, ResultData);
                    if (this.Callback != null)
                    {
                        this.Callback(ResultData, ErrorType.Err_Null);
                    }
                }
                catch (Exception ex)
                {
                    if (ResultData.ContainsKey("ErrorEntity"))
                    {
                        ErrorEntity errorEntity = ResultData["ErrorEntity"] as ErrorEntity;
                        errorEntity.ErrorMessage = ex.Message.ToString();
                        if (this.Callback != null)
                        {
                            this.Callback(ResultData, ErrorType.Err_WebException);
                        }
                    }

                }
                result = 0;
            }
            return result;
        }

        private void Abort()
        {
            if (this._httpClient != null)
            {
                this.Callback = null;
                this._httpClient.CancelPendingRequests();
                this._httpClient.Dispose();
            }
        }
        #endregion

        protected virtual void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                this.Abort();
            }
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);//不懂
        }
    }
}
